<template>
  <ele-table-select
    ref="selectRef"
    v-model="modelValue"
    clearable
    placeholder="请选择商品"
    value-key="id"
    label-key="order_sn"
    :table-props="tableProps"
    filterable
    :popper-width="580"
    @clear="selectClear"
    @filterChange="filterChange"
    @visibleChange="visibleChange"
    @select="select"
  />
</template>

<script setup>
const emit = defineEmits(['done'])

const modelValue = defineModel()

const selectRef = ref(null)

const keyword = ref('')

const datasource = ref([])

function selectReload() {
  const where = { keyword: keyword.value }
  selectRef.value?.tableRef?.reload?.({ where, page: 1 })
}

function selectClear() {
  keyword.value = ''
  selectReload()
  selectRef.value.selectVisible = true
}

function filterChange(value) {
  keyword.value = value
  selectReload()
}

function visibleChange(value) {
  if (value && !datasource.value.length) {
    selectClear()
  }
}

function select(data) {
  emit('done', data)
}

const tableProps = reactive({
  size: 'small',
  datasource: async ({ where, pages, orders }) => {
    const res = await utils.get('/purchaseReturn/purchase', { ...where, ...orders, ...pages })

    datasource.value = res.data
    return res
  },
  columns: [
    {
      type: 'index',
      columnKey: 'index',
      label: '序',
      width: 50,
      align: 'center',
      fixed: 'left',
    },
    {
      prop: 'order_sn',
      label: '采购单据',
      width: 160,
      showOverflowTooltip: false,
    },
    {
      prop: 'supplier_name',
      label: '货主',
      width: 100,
      align: 'center',
    },
    {
      prop: 'warehouse_name',
      label: '仓库',
      align: 'center',
      width: 100,
    },
    {
      prop: 'sup_sub_name',
      label: '供应商',
      align: 'center',
      width: 100,
    },
  ],
  highlightCurrentRow: true,
  loadOnCreated: false,
  toolbar: false,
  pagination: {
    pageSize: 6,
    layout: 'total, prev, pager, next, jumper',
  },
  footerStyle: { padding: '0px' },
  rowStyle: { cursor: 'pointer' },
})
</script>

<style lang="scss" scoped>

</style>
